<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="160px"
      v-loading="formLoading"
    >
      <el-form-item label="平台代码" prop="code">
        <el-input v-model="formData.code" placeholder="请输入平台代码" />
      </el-form-item>
      <el-form-item label="平台名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入平台名称" />
      </el-form-item>
      <el-form-item label="英文名称" prop="nameEn">
        <el-input v-model="formData.nameEn" placeholder="请输入英文名称" />
      </el-form-item>
      <el-form-item label="平台类型" prop="type">
        <el-select v-model="formData.type" placeholder="请选择平台类型">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_PLATFORM_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="平台区域代码" prop="region">
        <el-input v-model="formData.region" placeholder="请输入平台区域代码" />
      </el-form-item>
      <el-form-item label="国家代码" prop="countryCode">
        <el-input v-model="formData.countryCode" placeholder="请输入国家代码" />
      </el-form-item>
      <el-form-item label="平台官网地址" prop="platformUrl">
        <el-input v-model="formData.platformUrl" placeholder="请输入平台官网地址" />
      </el-form-item>
      <el-form-item label="API基础地址" prop="apiBaseUrl">
        <el-input v-model="formData.apiBaseUrl" placeholder="请输入API基础地址" />
      </el-form-item>
      <el-form-item label="API版本" prop="apiVersion">
        <el-input v-model="formData.apiVersion" placeholder="请输入API版本" />
      </el-form-item>
      <el-form-item label="认证类型" prop="authType">
        <el-select v-model="formData.authType" placeholder="请选择认证类型">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_AUTH_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="认证配置" prop="authConfig">
        <el-input v-model="formData.authConfig" placeholder="请输入认证配置，JSON格式" />
      </el-form-item>
      <el-form-item label="频率限制" prop="rateLimitConfig">
        <el-input v-model="formData.rateLimitConfig" placeholder="请输入频率限制配置，JSON格式" />
      </el-form-item>
      <el-form-item label="支持货币代码" prop="supportedCurrencies">
        <el-input v-model="formData.supportedCurrencies" placeholder="请输入支持的货币代码，使用逗号分隔" />
      </el-form-item>
      <el-form-item label="支持语言代码" prop="supportedLanguages">
        <el-input v-model="formData.supportedLanguages" placeholder="请输入支持的语言代码，使用逗号分隔" />
      </el-form-item>
      <el-form-item label="费率配置" prop="feeConfig">
        <el-input v-model="formData.feeConfig" placeholder="请输入费率配置，JSON格式" />
      </el-form-item>
      <el-form-item label="同步配置" prop="syncConfig">
        <el-input v-model="formData.syncConfig" placeholder="请输入同步配置，JSON格式" />
      </el-form-item>
      <el-form-item label="Webhook配置" prop="webhookConfig">
        <el-input v-model="formData.webhookConfig" placeholder="请输入Webhook配置，JSON格式" />
      </el-form-item>
      <el-form-item label="功能特性" prop="features">
        <el-input v-model="formData.features" placeholder="请输入支持的功能特性，JSON格式" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="formData.status" placeholder="请选择状态">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_COMMON_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否启用" prop="enabled">
        <el-select v-model="formData.enabled" placeholder="请选择是否启用">
          <el-option
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="String(dict.value)"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model="formData.sort" placeholder="请输入排序" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions, getBoolDictOptions } from '@/utils/dict'
import { PlatformConfigApi, PlatformConfigVO } from '@/api/crossborder/platformconfig'

/** 跨境电商平台配置 表单 */
defineOptions({ name: 'PlatformConfigForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  code: undefined,
  name: undefined,
  nameEn: undefined,
  type: undefined,
  region: undefined,
  countryCode: undefined,
  platformUrl: undefined,
  apiBaseUrl: undefined,
  apiVersion: undefined,
  authType: undefined,
  authConfig: undefined,
  rateLimitConfig: undefined,
  supportedCurrencies: undefined,
  supportedLanguages: undefined,
  feeConfig: undefined,
  syncConfig: undefined,
  webhookConfig: undefined,
  features: undefined,
  status: undefined,
  enabled: undefined,
  sort: undefined,
  remark: undefined,
})
const formRules = reactive({
  code: [{ required: true, message: '平台代码不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '平台名称不能为空', trigger: 'blur' }],
  type: [{ required: true, message: '平台类型（1电商平台 2社交电商 3自建商城）不能为空', trigger: 'change' }],
  apiBaseUrl: [{ required: true, message: 'API基础地址不能为空', trigger: 'blur' }],
  authType: [{ required: true, message: '认证类型（1OAuth2 2API密钥 3JWT 4Basic Auth）不能为空', trigger: 'change' }],
  status: [{ required: true, message: '状态（0正常 1停用）不能为空', trigger: 'blur' }],
  enabled: [{ required: true, message: '是否启用不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await PlatformConfigApi.getPlatformConfig(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as PlatformConfigVO
    if (formType.value === 'create') {
      await PlatformConfigApi.createPlatformConfig(data)
      message.success(t('common.createSuccess'))
    } else {
      await PlatformConfigApi.updatePlatformConfig(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    code: undefined,
    name: undefined,
    nameEn: undefined,
    type: undefined,
    region: undefined,
    countryCode: undefined,
    platformUrl: undefined,
    apiBaseUrl: undefined,
    apiVersion: undefined,
    authType: undefined,
    authConfig: undefined,
    rateLimitConfig: undefined,
    supportedCurrencies: undefined,
    supportedLanguages: undefined,
    feeConfig: undefined,
    syncConfig: undefined,
    webhookConfig: undefined,
    features: undefined,
    status: undefined,
    enabled: undefined,
    sort: undefined,
    remark: undefined,
  }
  formRef.value?.resetFields()
}
</script>